package userfav

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"web/userop/api"
	"web/userop/forms"
	"web/userop/global"
	"web/userop/proto"
)

// 用户将商品添加至"我的收藏"
func AddUserfav(ctx *gin.Context) {
	f := new(forms.UserFavForm)
	if err := ctx.ShouldBind(&f); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	var userId int32
	if val, ok := ctx.Get("userId"); ok {
		userId = val.(int32)
	} else {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"msg": "请重新登录",
		})
		return
	}

	_, err := global.UseropSrvClient.AddUserFav(context.Background(), &proto.UserFavRequest{
		UserId:  userId,
		GoodsId: f.GoodsId,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		zap.S().Error("添加收藏失败：", err)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "收藏成功",
	})
}

// 用户将商品取消收藏
func DeleteUserfav(ctx *gin.Context) {
	f := new(forms.UserFavForm)
	if err := ctx.ShouldBind(&f); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	var userId int32
	if val, ok := ctx.Get("userId"); ok {
		userId = val.(int32)
	} else {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"msg": "请重新登录",
		})
		return
	}

	_, err := global.UseropSrvClient.DeleteUserFav(context.Background(), &proto.UserFavRequest{
		UserId:  userId,
		GoodsId: f.GoodsId,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		zap.S().Error("取消收藏失败：", err)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "取消收藏成功",
	})
}
